<template>
  <div class="comparisonAverage">
    <div class="header">
      <BasicForm @register="register" @submit="getStationData" style="width: 100%" />
    </div>
    <!-- 内容区域 -->
    <div class="content">
      <!-- 图表 -->
      <TableChart
        :chartOption="state.chartOption"
        :isShowTable="state.isShowTable"
        :isShowTipIndex="state.isShowTipIndex"
      />
      <!-- 侧边栏内容区域 -->
      <div class="basicInfoTableList" :class="{ isShowTable: !state.isShowTable }">
        <TableList
          :tableDataSource="state.tableDataSource"
          :tableColumns="state.tableColumns"
          rowKey="time"
          @cellClick="cellClick"
        />
        <!-- 显示隐藏侧边栏内容区域 -->
        <div
          class="showTableBtn"
          :class="{ isRotate: !state.isShowTable }"
          @click="state.isShowTable = !state.isShowTable"
        >
          <Icon icon="tabler:caret-left-filled" size="20" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, watch, inject, onMounted } from "vue";
  import dayjs from "dayjs";
  import TableChart from "@/components/TableChart";
  import TableList from "@/components/TableList";
  import setChartOption from "./comparisonAverageChartOption";
  import { Icon } from "@gui-pkg/components";
  import { BasicForm, FormSchema, useForm } from "@gui-pkg/antdcomponents";
  import { getRsvrByYrAndFilter } from "@/api/realTime/realData";

  defineOptions({ name: 'ComparisonAverage' });

  const year = dayjs().format("YYYY");
  const yearOptions = [...Array(10)].map((_, i) => ({ value: year - i }));
  const schemas: FormSchema[] = [
    {
      field: 'dataType',
      label: '类型选择',
      component: 'Select',
      colProps: { span: 5 },
      defaultValue: '1',
      componentProps: {
        options: [
          { label: '平均水位', value: '1', key: '1' },
          /*{ label: '平均流量', value: '2', key: '2' },*/
          { label: '平均蓄水量', value: '3', key: '3' },
        ],
      },
    },
    {
      field: 'timeType',
      label: '旬月选择',
      component: 'Select',
      colProps: { span: 4 },
      defaultValue: '2',
      componentProps: {
        options: [
          { label: '一日', value: '3', key: '3' },
          { label: '一旬', value: '2', key: '2' },
          { label: '一月', value: '1', key: '1' },
        ],
      },
    },
    {
      field: "years",
      label: "对比年",
      component: "Select",
      colProps: { span: 8 },
      defaultValue: [Number(year), year - 1, year - 2],
      componentProps: {
        mode: "multiple",
        maxTagCount: 3,
        maxTagTextLength: 4,
        options: yearOptions,
      },
    },
  ];

  const [register, { getFieldsValue }] = useForm({
    labelWidth: 80,
    schemas,
    actionColOptions: { span: 4 },
  });

  const props = defineProps({
    data: { type: Object },
  });

  const state = reactive({
    isShowTable: true,
    chartOption: null,
    isShowTipIndex: -1,
    tableDataSource: [],
    tableColumns: [{ dataIndex: "time", title: "标志时间", align: "center" }],
  });

  const cellClick = ({ params, index }) => {
    state.isShowTipIndex = state.tableDataSource.length - index - 1;
  };

  // 转换旬月数据
  function transformData(data) {
    const years = []; // 用于存储所有年份
    const timeSlots = {}; // 用于存储所有时间段
    // 遍历数据，收集所有年份和时间段
    data.forEach(item => {
      if (!years.includes(item.yr)) {
        years.push(item.yr);
      }
      item.data.forEach(point => {
        if (!timeSlots[point.time]) {
          timeSlots[point.time] = {};
        }
        timeSlots[point.time][item.yr] = point.value;
      });
    });
    // 构建结果数组
    const result = [];
    for (const time in timeSlots) {
      const record = {};
      for (const year of years) {
        record[year] = timeSlots[time][year] || null;
      }
      record.time = time;
      result.push(record);
    }
    return result;
  }

  // 转换旬月数据中的： 一日
  function transformDayData(data) {
    let data2 = [];
    let years = new Set();
    data.forEach(yearData => {
      years.add(yearData.yr);
      yearData.data.forEach(dayData => {
        let day = dayData.time.split('-').slice(1).join('-');
        let existingDay = data2.find(d => d.time === day);
        if (existingDay) {
          existingDay[yearData.yr] = dayData.value;
        } else {
          let newDay = {time: day};
          newDay[yearData.yr] = dayData.value;
          data2.push(newDay);
        }
      });
    });
    data2.forEach(day => {
      years.forEach(year => {
        if (day[year] === undefined) {
          day[year] = null;
        }
      });
    });
    return data2;
  }

  // 后台获取站点数据
  const getStationData = async (data = null) => {
    if (props?.data?.stcd) {
      const params = {
        // stcd: props?.data?.stcd,
        dataType: data?.dataType,
        timeType: data?.timeType,
        yr: data?.years.join(","),
      };
      const stationData = await getRsvrByYrAndFilter(params);
      let dataSourceData = [];
      let tableColumns = [{ dataIndex: "time", title: "标志时间", align: "center" }];
      for (let i = 0; i < stationData.length; i++) {
        tableColumns.push({ dataIndex: stationData[i].yr, title: stationData[i].yr, align: "center" });
      }
      if (data?.timeType === '3') {
        dataSourceData = transformDayData(stationData);
      }else {
        dataSourceData = transformData(stationData);
      }
      state.tableColumns = tableColumns;
      state.tableDataSource = dataSourceData;
      state.chartOption = setChartOption(dataSourceData, params, props.data);
    }
  }

  // 初始化数据
  const initData = async () => {
    const values = await getFieldsValue();
    if (!values.dataType) {
      const year = dayjs().format("YYYY");
      values.dataType = '1';
      values.timeType = '2';
      values.years = [Number(year), year - 1, year - 2];
    }
    await getStationData(values);
  };

  // 监听是否点击了全屏，重新渲染下
  const modalHeightChange = inject("ModalHeightChange");
  watch(
    () => modalHeightChange.value,
    () => {
      initData();
    }
  );

  onMounted(() => {
    initData();
  });
</script>

<style lang="less" rel="stylesheet/less" scoped>
  .comparisonAverage {
    width: 100%;
    height: 100%;
    .header {
      width: 100%;
      height: 32px;
      display: flex;
      align-items: center;
      margin-bottom: 18px;
      ::v-deep(.ant-form-item) {
        margin-bottom: 0 !important;
      }
      .step {
        margin-left: 10px;
        margin-right: 30px;
      }
    }
    .content {
      width: 100%;
      height: calc(100% - 50px);
      display: flex;
      align-items: center;
      position: relative;
      .basicInfoTableList {
        width: 390px;
        height: 100%;
        display: flex;
        flex-direction: column;
        position: absolute;
        right: 0;
        transition: all 0.5s;
      }
      .showTableBtn {
        position: absolute;
        top: 40%;
        left: -22px;
        z-index: 200;
        width: 24px;
        height: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        border-radius: 6px;
        transition: all 0.5s;
        transform: translate(0px, -50%) rotate(180deg);
        background: url(@/assets/svg/sideBar.svg) no-repeat;
        span {
          margin-top: -20px;
          font-size: 18px;
          color: #c4c4c4;
          transform: rotate(0deg);
          transition: all 0.3s;
        }
        &:hover {
          span {
            color: #5780fa;
          }
        }
      }
      .isRotate {
        span {
          transform: rotate(180deg);
        }
      }
    }
    .isShowTable {
      right: -390px !important;
    }
  }
</style>
